package syllabus.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import syllabus.commons.AttachFile;
import syllabus.commons.ExtReturn;
import syllabus.model.PFile;
import syllabus.model.PSyllabus;
import syllabus.service.PFileService;
import syllabus.shiro.ShiroDbRealm;

@Controller
public class CommonUploadAct {

	private static final Logger logger = LoggerFactory.getLogger(CommonUploadAct.class);
	@Autowired
	private PFileService fileService;
	/**
	 * 保存路径
	 */
	private static final String UPLOAD_PATH = "/upload/";
	/**
	 * 缩略图保存路径
	 */
	private static final String UPLOAD_PATH_THUMBNAIL = "/thumbnail";
	
	private static final List<String> imageTypes = Arrays.asList("jpg","png","gif","bmp","jpeg");
	/**
	 * uploadify工具只接受返回的字符串，所以使用response方法
	 * @param file_upload
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value = "/common/upload", method = RequestMethod.POST )
	public void upload(@RequestParam(value = "file_upload", required = false)MultipartFile file_upload,
			HttpServletRequest request,HttpServletResponse response, ModelMap model) throws IOException{
		
		//System.out.println(request.getSession().getId());
		response.setContentType("text/plain;charset=utf-8");
		
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
		String dir = sdf.format(new Date());
		// 创建文件保存位置   
		ServletContext context = request.getSession().getServletContext();  
        String savePath = UPLOAD_PATH + dir;
        //String thumbSavePath = UPLOAD_PATH + dir + UPLOAD_PATH_THUMBNAIL;
        
		String saveRealPath = context.getRealPath(savePath);  
        //String thumbSaveRealPath = context.getRealPath(UPLOAD_PATH + dir + UPLOAD_PATH_THUMBNAIL);  

        File folder = new File(saveRealPath );  
        if (!folder.exists()) {  
            folder.mkdirs();  
        }

        logger.info("文件保存路径：{}", saveRealPath);  
		// 保存文件的名称
		String rndFilename = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
		// 文件名称
		String origName = file_upload.getOriginalFilename();
		// 文件扩展名
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		//是否图片
		boolean isImage = imageTypes.contains(ext);
		//文件大小
		long size = file_upload.getSize()/1024;//kb   
		
		//真实文件路径
		String fileNameAndPath = saveRealPath+"/"+rndFilename + "." + ext;
		//String thumbNewFile = thumbSaveRealPath + "/"+rndFilename + "." + ext;
		
		File newFile = new File(fileNameAndPath); 
		
		//相对路径
		String attrPath = savePath + "/"+rndFilename + "." + ext;
		//String thumbAttrPath = thumbSavePath + "/"+rndFilename + "." + ext;
		
		try {  
			file_upload.transferTo(newFile);   
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
		
		Subject suser = SecurityUtils.getSubject();
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser)suser.getPrincipal();
		
		PFile att = new PFile();
		att.setFileName(origName);
		att.setFileSize(size);
		att.setFilePath(attrPath);
		att.setTg(PFile.TG_CHECK);
		att.setGxsj(new Date());
		att.setUploadUser(shiroUser.loginName);
		
		fileService.insertSelective(att);
		
		
		ExtReturn obj = new ExtReturn();
		obj.setSuccess(ExtReturn.SUCCESS);
		obj.setMsg("success!");
		obj.setO(att);
		//输出json，格式为string
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(),obj );
		
	}
}
